/**
 * AddRoleController.java
 */
package org.yate.oa.controller;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.yate.oa.model.PrivilegeEntity;
import org.yate.oa.model.RoleEntity;
import org.yate.oa.service.IPrivilegeService;
import org.yate.oa.service.IRoleService;
import org.yate.oa.utils.Pagination;

/**
 * @author Yate
 * @date Nov 19, 2013
 * @description TODO
 * @version 1.0
 */
@WebServlet(urlPatterns = { "/role/add" }, asyncSupported = true )
public class AddRoleController extends BaseServletController {
	
	private IRoleService roleService;
	private IPrivilegeService privService;

	/* 
	 * (non-Javadoc)
	 * @see org.yate.oa.controller.BaseController#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.roleService = (IRoleService) this.springCtx.getBean("roleService");
		this.privService = (IPrivilegeService) this.springCtx.getBean("privilegeService");
	}

	/* 
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Pagination<PrivilegeEntity> pd =  this.privService.getEntities(1, Integer.MAX_VALUE, "", "");
		req.setAttribute("privs", pd);
		req.getRequestDispatcher("/jsp/roles/add.jsp").forward(req, resp);
	}

	/* 
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String name = req.getParameter("roleName");
		String[] privs = req.getParameterValues("priv");
		
		this.roleService.add(new RoleEntity(name), privs);
		
		req.getRequestDispatcher("/role/get").forward(req, resp);
	}

	
}
